package com.jic.product.controller.rest;

import com.alibaba.fastjson.JSONArray;
import com.jic.common.base.vo.Page;
import com.jic.common.base.vo.PageResult;
import com.jic.common.base.vo.RestResult;
import com.jic.common.redis.RedisClientTemplate;
import com.jic.common.utils.DateUtils;
import com.jic.enums.RedisKey;
import com.jic.manager.api.manage.SysDeptApi;
import com.jic.manager.request.SysDeptRequest;
import com.jic.manager.response.MemStoreResponse;
import com.jic.market.api.after.MarketApi;
import com.jic.market.api.rest.RealTimePriceRestApi;
import com.jic.market.request.PromotionPolymericRequest;
import com.jic.market.request.rest.PresellProductRequest;
import com.jic.market.request.rest.groupon.GrouponInfoRequest;
import com.jic.market.request.rest.realtimeprice.RealTimePriceRequest;
import com.jic.market.request.rest.seckill.SeckillInfoRequest;
import com.jic.market.response.PresellProductResponse;
import com.jic.market.response.PromotionSingleProductResponse;
import com.jic.market.response.rest.SeckillInfoResponse;
import com.jic.market.response.rest.groupon.GroupInfoFeignResponse;
import com.jic.market.response.rest.groupon.GrouponInfoResponse;
import com.jic.market.response.rest.realtimeprice.RealTimePriceListResponse;
import com.jic.member.api.rest.MemberFavoriteManangeRestApi;
import com.jic.member.request.MemberFavoriteRestRequest;
import com.jic.member.request.MememberUserRequest;
import com.jic.product.controller.rest.request.QueryProductByStoreIdRequest;
import com.jic.product.entity.Product;
import com.jic.product.manage.request.ProductDetailRequest;
import com.jic.product.manage.response.ShopInfoResponse;
import com.jic.product.rest.request.ProductRestRequest;
import com.jic.product.rest.response.*;
import com.jic.product.service.*;
import com.jic.util.DateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by HeJun on 2020/1/18
 *
 * @Description:
 */
@Api(value = "API-商品管理", tags = "API-商品管理")
@RestController
@RequestMapping("/productRest")
@Slf4j
public class ApiProductRest {

    @Autowired
    ProductService productService;
    @Autowired
    ProductGuaranteeRelationService productGuaranteeRelationService;
    @Autowired
    ProductMediaService productMediaService;
    @Autowired
    ProductSkuService productSkuService;

    @Autowired
    StoreInventoryService storeInventoryService;

    @Resource
    MemberFavoriteManangeRestApi memberFavoriteManangeRestApi;

    @Autowired
    private RedisClientTemplate redisClientTemplate;

    @Resource
    SysDeptApi sysDeptApi;

    @Resource
    RealTimePriceRestApi realTimePriceRestApi;

    @Resource
    private MarketApi marketApi;


    @ApiOperation(value = "查询PC首页商品", notes = "查询首页商品")
    @PostMapping("/getHomeProducts")
    public RestResult<List<ProductResponseFront>> getHomeProducts() {
        List<ProductResponseFront> result = productService.queryRecommendedProducts();
        result.forEach(item -> {
            List<String> codes = new ArrayList<>();
            codes.add(item.getCode());
            RealTimePriceRequest realTimePriceRequest = new RealTimePriceRequest();
            realTimePriceRequest.setThirdProductCodes(codes);
            RestResult<RealTimePriceListResponse> priceStockList = realTimePriceRestApi.getPriceStockList(realTimePriceRequest);
            if (null != priceStockList && null != priceStockList.getData() && CollectionUtils.isNotEmpty(priceStockList.getData().getRealTimePrices())) {
                item.setMarketPrice(new BigDecimal(priceStockList.getData().getRealTimePrices().get(0).getAvailablePrice()));
            }
        });
        return RestResult.success(result);
    }

    @ApiOperation(value = "H5推荐商品列表", notes = "推荐商品列表")
    @PostMapping("/getRecommendedProductList")
    public RestResult<List<ProductResponseFront>> getRecommendedProductList() {
        List<ProductResponseFront> result = productService.queryRecommendedProducts();
        return RestResult.success(result);
    }

    @ApiOperation(value = "选择规格属性", notes = "选择规格属性")
    @PostMapping("/getProductsProperty")
    public RestResult<List<ProductPropertyResponseFront>> getProductsProperty(long id) {
        List<ProductPropertyResponseFront> result = productService.queryProductsPropertyById(id);
        return RestResult.success(result);
    }


    @ApiOperation(value = "查询前台商品详情", notes = "查询前台商品详情")
    @PostMapping("/queryProductDetail")
    public RestResult<ProductDetailResponse> queryProductDetail(@RequestBody ProductDetailRequest productDetailResult) {
        ProductDetailResponse productDetailResponse = new ProductDetailResponse();
        try {
            String userStr = redisClientTemplate.get(RedisKey.H5_LOGIN_TOKEN_.getName() + productDetailResult.getToken());
            MememberUserRequest mMember = JSONArray.parseObject(userStr, MememberUserRequest.class);
            //查询商品基本信息
            ProductInfoResponse productInfoResponse = productService.queryByProductId(productDetailResult.getId());
            if (productInfoResponse == null) {
                return RestResult.error("9999", "商品已下架，请重新选择其它商品！");
            }
            if (mMember != null) {
                productInfoResponse.setMemberId(mMember.getId());
            }
            if (productInfoResponse.getTypeOfProduct() == 3) {
                ProductInfoResponse productInfoResponse1 = productService.queryByProductId(productInfoResponse.getParentId());
                BeanUtils.copyProperties(productInfoResponse1, productInfoResponse);
            }
            productInfoResponse.setMarketPrice(productInfoResponse.getSalePriceWithTax());
            //判断商品是否秒杀商品
            if (productDetailResult.getProductType() != null) {
                switch (productDetailResult.getProductType()) {
                    case 1:
                        SeckillInfoRequest seckillInfoRequest = new SeckillInfoRequest();
                        seckillInfoRequest.setGoodsId(productDetailResult.getId());
                        seckillInfoRequest.setPromotionId(Long.valueOf(productDetailResult.getPromotionId()));
                        RestResult<SeckillInfoResponse> seckillInfoResponseRestResult = marketApi.getSecondsKillInfo(seckillInfoRequest);
                        SeckillInfoResponse seckillInfoResponse = seckillInfoResponseRestResult.getData();
                        if (seckillInfoResponse != null) {
                            //营销价
                            productInfoResponse.setMarketPrice(seckillInfoResponse.getPromPrice());
                            productInfoResponse.setSetActivityEndTime(seckillInfoResponse.getEndTime());
                            String startTimeStr = DateUtil.getDateStr(new Date())+ " " +seckillInfoResponse.getStartTime()+":00";
                            productInfoResponse.setStartTimeStr(startTimeStr);
                            productInfoResponse.setStartTime(DateUtil.getDateFromMin(startTimeStr).getTime());
                            String endTimeStr = DateUtil.getDateStr(new Date())+ " " +seckillInfoResponse.getEndTime()+":00";
                            productInfoResponse.setEndTimeStr(endTimeStr);
                            productInfoResponse.setEndTime(DateUtil.getDateFromMin(endTimeStr).getTime());
                            productInfoResponse.setTimeId(seckillInfoResponse.getTimeId());
                        }
                        break;
                    case 2:
                        //拼团信息
                        GrouponInfoRequest request = new GrouponInfoRequest();
                        request.setGroupCode(productDetailResult.getPromotionId());
                        request.setThirdProductCode(productInfoResponse.getThirdProductCode());
                        request.setProductType(10);
                        RestResult<GrouponInfoResponse> responseRestResult = marketApi.getGroupInfo(request);
                        GrouponInfoResponse groupInfoFeignResponse = responseRestResult.getData();
                        if (groupInfoFeignResponse != null) {
                            //营销价
                            productInfoResponse.setMarketPrice(groupInfoFeignResponse.getAvailablePrice());
                            productInfoResponse.setStartTimeStr(groupInfoFeignResponse.getStartTimeStr());
                            productInfoResponse.setEndTimeStr(groupInfoFeignResponse.getEndTimeStr());
                            productInfoResponse.setStartTime(groupInfoFeignResponse.getStartTime());
                            productInfoResponse.setEndTime(groupInfoFeignResponse.getEndTime());
                            productInfoResponse.setGroupMembers(groupInfoFeignResponse.getGroupMembers());
                            productInfoResponse.setActivityRemark(groupInfoFeignResponse.getDescription());
                        }
                        break;
                }
            }
            // 查询商品是否参与预售活动
            PresellProductRequest presellProductRequest = new PresellProductRequest();
            presellProductRequest.setMpId(productDetailResult.getId());
            RestResult<PresellProductResponse> productResponseRestResult = marketApi.queryPresellByMpId(presellProductRequest);
            PresellProductResponse presellProductResponse = productResponseRestResult.getData();
            if (presellProductResponse != null){
                productInfoResponse.setIsPresale(1);
                productInfoResponse.setMarketPrice(presellProductResponse.getSalePriceWithTax());
                productInfoResponse.setStartTime(presellProductResponse.getStartTime().getTime());
                productInfoResponse.setStartTimeStr(DateUtils.convert(presellProductResponse.getStartTime()));
                productInfoResponse.setEndTime(presellProductResponse.getEndTime().getTime());
                productInfoResponse.setEndTimeStr(DateUtils.convert(presellProductResponse.getEndTime()));
                productInfoResponse.setSendGoodsTime(presellProductResponse.getSendGoodsTime().getTime());
            }else {
                productInfoResponse.setIsPresale(2);
            }

            // 查询商品是否参与单一促销
            PromotionPolymericRequest promotionPolymericRequest = new PromotionPolymericRequest();
            promotionPolymericRequest.setMpId(productDetailResult.getId());
            RestResult<PromotionSingleProductResponse> singleProductResponseRestResult = marketApi.querySingleByMpId(promotionPolymericRequest);
            PromotionSingleProductResponse promotionSingleProductResponse = singleProductResponseRestResult.getData();
            if (promotionSingleProductResponse != null){
                if(promotionSingleProductResponse.getFrontPromType().toString().equals("1")){
                    productInfoResponse.setMarketPrice(promotionSingleProductResponse.getContentValue());
                }else if(promotionSingleProductResponse.getFrontPromType().toString().equals("2")){
                    BigDecimal discount =  promotionSingleProductResponse.getContentValue().divide(new BigDecimal("10"));
                    productInfoResponse.setMarketPrice(productInfoResponse.getSalePriceWithTax().multiply(discount));
                }else if(promotionSingleProductResponse.getFrontPromType().toString().equals("3")){
                    productInfoResponse.setMarketPrice(productInfoResponse.getSalePriceWithTax().subtract(promotionSingleProductResponse.getContentValue()));
                }
            }
            //店铺信息
            if (0 != productInfoResponse.getDeptId()) {
                SysDeptRequest sysDeptRequest = new SysDeptRequest();
                sysDeptRequest.setId(productInfoResponse.getDeptId());
                RestResult<MemStoreResponse> storeInfo = sysDeptApi.getStoreInfoByDeptId(sysDeptRequest);
                if (null != storeInfo && null != storeInfo.getData()) {
                    MemStoreInfoResponse memStoreInfoResponse = new MemStoreInfoResponse();
                    BeanUtils.copyProperties(storeInfo.getData(), memStoreInfoResponse);
                    MemberFavoriteRestRequest memberFavoriteRestRequest = new MemberFavoriteRestRequest();
                    memberFavoriteRestRequest.setDeptId(productInfoResponse.getDeptId());
                    RestResult restResult = memberFavoriteManangeRestApi.queryFollowersByDeptId(memberFavoriteRestRequest);
                    //查询当前商品是否收藏
                    if (null != mMember) {
                        MemberFavoriteRestRequest favority = new MemberFavoriteRestRequest();
                        favority.setMemberId(mMember.getId());
                        favority.setEntityId(storeInfo.getData().getId());
                        Boolean boosStore = memberFavoriteManangeRestApi.queryFollowersByEntityId(favority);
                        if (true == boosStore) {
                            memStoreInfoResponse.setIsFavorite("1");
                        } else {
                            memStoreInfoResponse.setIsFavorite("0");
                        }
                    }

                    if (null != restResult) {
                        memStoreInfoResponse.setFollowersNumber(Long.valueOf(restResult.getData().toString()));
                        productDetailResponse.setMemStoreInfo(memStoreInfoResponse);
                    }
                    productDetailResponse.setMemStoreInfo(memStoreInfoResponse);
                }
            }
            if (null != mMember) {

                MemberFavoriteRestRequest favority = new MemberFavoriteRestRequest();
                favority.setEntityId(productDetailResult.getId());
                favority.setMemberId(mMember.getId());
                Boolean boosProduct = memberFavoriteManangeRestApi.queryFollowersByEntityId(favority);
                if (true == boosProduct) {
                    productInfoResponse.setIsFavoriteProduct("1");
                } else {
                    productInfoResponse.setIsFavoriteProduct("0");
                }
            }
            //营销价
//            List<String> codes = new ArrayList<>();
//            codes.add(productInfoResponse.getCode());
//            RealTimePriceRequest realTimePriceRequest = new RealTimePriceRequest();
//            realTimePriceRequest.setThirdProductCodes(codes);
//            RestResult<RealTimePriceListResponse> priceStockList = realTimePriceRestApi.getPriceStockList(realTimePriceRequest);
//            if (null != priceStockList && null != priceStockList.getData() && CollectionUtils.isNotEmpty(priceStockList.getData().getRealTimePrices()) && !priceStockList.getData().getRealTimePrices().get(0).getAvailablePrice().equals("")) {
//                productInfoResponse.setMarketPrice(priceStockList.getData().getRealTimePrices().get(0).getAvailablePrice());
//            } else {
//                productInfoResponse.setMarketPrice(String.valueOf(productInfoResponse.getSalePriceWithTax().intValue()));
//            }

            //已售数量 1-普通商品;2-系列子品  库存
            List<Long> productIds = new ArrayList<>();
            if (productInfoResponse.getTypeOfProduct() == 2) {
                Product product = new Product();
                product.setDeleteFlag(0);
                product.setParentId(productInfoResponse.getId());
                List<Product> productList = productService.query(product);
                productList.forEach(item -> {
                    productIds.add(item.getId());
                });
            } else {
                productIds.add(productInfoResponse.getId());
            }
            //库存
            if (CollectionUtils.isNotEmpty(productIds)) {
                Integer integer = storeInventoryService.queryByProductIds(productIds);
                productInfoResponse.setAvailableStock(integer);
            }
            productDetailResponse.setProductInfo(productInfoResponse);

            //查询商品保障
            List<ProductGuaranteeResponse> productGuaranteeResponses = productGuaranteeRelationService.queryByProductId(productInfoResponse.getId());
            productDetailResponse.setProductGuaranteeList(productGuaranteeResponses);

            //查询商品媒介
            List<ProductMediaResponse> productMediaResponses = productMediaService.queryByProductId(productInfoResponse.getId());
            productDetailResponse.setProductMedia(productMediaResponses);

        } catch (Exception e) {
            log.error("error", e);
            return RestResult.error("9999", e.getLocalizedMessage());
        }
        return RestResult.success(productDetailResponse);

    }

    @PostMapping("/getSkuList")
    @ApiOperation(value = "通过productId获取商品全部规格列表", notes = "通过productId获取商品全部规格列表")
    public RestResult<List<ProductSkuResponse>> getSkuListByProdId(Long productId,String promotionId) {
        return productService.getSkuListByProdId(productId,promotionId);
    }


    @PostMapping("/queryPorductByStoreId")
    @ApiOperation(value = "通过店铺deptId获取商品信息", notes = "通过店铺deptId获取商品信息")
    public RestResult<PageResult<ProductDetailResponse>> queryPorductByStoreId(@RequestBody QueryProductByStoreIdRequest request) {
        Page page = new Page();
        page.setLimit(request.getLimit());
        page.setStart(request.getStart());
        Product product = new Product();
        product.setDeptId(request.getDeptId());
        PageResult<ShopInfoResponse> pageResult = productService.queryPorductByStoreId(product, page);
        List<ProductDetailResponse> res = new ArrayList<>();
        pageResult.getRows().forEach(shopInfoResponse -> {
            ProductDetailResponse productDetailResponse = new ProductDetailResponse();
            ProductInfoResponse productInfo = new ProductInfoResponse();
            productInfo.setName(shopInfoResponse.getChineseName());
            productInfo.setId(shopInfoResponse.getId());
            productInfo.setDeptId(request.getDeptId());
            //营销价格需要调用营销中心接口
            List<String> codes = new ArrayList<>();
            codes.add(shopInfoResponse.getCode());
            RealTimePriceRequest realTimePriceRequest = new RealTimePriceRequest();
            realTimePriceRequest.setThirdProductCodes(codes);
            RestResult<RealTimePriceListResponse> priceStockList = realTimePriceRestApi.getPriceStockList(realTimePriceRequest);
            if (null != priceStockList && null != priceStockList.getData() && CollectionUtils.isNotEmpty(priceStockList.getData().getRealTimePrices()) && !priceStockList.getData().getRealTimePrices().get(0).getAvailablePrice().equals("")) {
                shopInfoResponse.setMarketPrice(priceStockList.getData().getRealTimePrices().get(0).getAvailablePrice());
            } else {
                shopInfoResponse.setMarketPrice(String.valueOf(shopInfoResponse.getSalePriceWithTax().intValue()));
            }

            productInfo.setSalePriceWithTax(shopInfoResponse.getSalePriceWithTax());

            List<ProductMediaResponse> imgList = new ArrayList<>();
            ProductMediaResponse productMediaResponse = new ProductMediaResponse();
            productMediaResponse.setPictureUrl(shopInfoResponse.getPictureUrl());
            imgList.add(productMediaResponse);

            productDetailResponse.setProductInfo(productInfo);
            productDetailResponse.setProductMedia(imgList);
            res.add(productDetailResponse);
        });
        return RestResult.success(new PageResult<ProductDetailResponse>() {{
            setRows(res);
            setTotal(pageResult.getTotal());
        }});
    }


    @PostMapping("/queryRestPorduct")
    @ApiOperation(value = "获取商品信息", notes = "获取商品信息")
    public RestResult<PageResult<List<ProductResponseFront>>> queryRestPorduct(@RequestBody ProductRestRequest productRestRequest) {
        return RestResult.success(productService.queryRestPorduct(productRestRequest));
    }

    @ApiOperation(value = "分享商品", notes = "分享商品")
    @PostMapping("/shareGoods")
    public RestResult<Long> shareGoods(ProductDetailRequest productDetailResult) {
        String userStr = redisClientTemplate.get(RedisKey.H5_LOGIN_TOKEN_.getName() + productDetailResult.getToken());
        if (StringUtils.isEmpty(userStr)) {
            return RestResult.error("4000", "非法请求");
        }
        MememberUserRequest mMember = JSONArray.parseObject(userStr, MememberUserRequest.class);
        return RestResult.success(mMember.getId());
    }

    @PostMapping("/queryGoodsByType")
    @ApiOperation(value = "根据类型活动商品列表",notes = "根据类型活动商品列表")
    @ResponseBody
    public RestResult<List<ProductInfoResponse>> queryGoodsByType(@RequestBody ProductDetailRequest request){
        return productService.queryGoodsByType(request);
    }

}
